/**
 * axios请求配置文件
 * @param
 * @returns
 */

import axios from "axios";
import { API_URL } from "@/config/envConfig";
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse } from "axios";
import NProgress from "@/plugins/progress";
import { ElMessage } from "element-plus";
import { getToken } from "@/utils/auth";
// import { useRouter } from "vue-router";
import router from "@/router";
import tools from "@/utils/tools";

// const router = useRouter();
/* 创建axios实例 */
const service: AxiosInstance = axios.create({
  baseURL: API_URL, // 请求基础地址
  timeout: 15000, // 请求超过时间
  withCredentials: true,
});

/* 请求接口前，做一些数据处理（请求拦截器） */
service.interceptors.request.use(
  async (config) => {
    NProgress.start(); // 每次请求时，调用进度条
    return config;
  },
  (error: any) => {
    console.error("error", error);
    NProgress.done();
    return Promise.resolve(error);
  }
);

/* 请求接口后，返回数据进行拦截（响应拦截器） */
service.interceptors.response.use(
  (response: AxiosResponse) => {
    const token = response.headers.token || response.headers.Token || "";
    ElMessage.closeAll();
    NProgress.done();

    const mesesageData = { msg: "" };
    // 业务拦截处理
    let data = response.data;
    switch (data?.code) {
      case 200:
        break;
      case 401:
        data = null;
        break;
      case 404:
        // 商品详情无商品跳转404
        router.replace("/404");
        break;
      case 600:
        mesesageData.msg = data.msg || "Request failed, please try again~~";
        ElMessage.error(mesesageData.msg);
        break;
      default:
        break;
    }
    setTimeout(() => {
      tools.translate();
    }, 800);
    return data ? data : Promise.resolve(data || mesesageData);
  },
  (error: any) => {
    // 错误响应
    NProgress.done();
    if (error && error.request && error.request.status == 401) {
    }
    if (error && error.request && error.request.status == 400) {
    }
    return Promise.resolve(error);
  }
);

export default service;

export const getCode = (response, msgFlag = true) => {
  ElMessage.closeAll();
  if (response && response.code == 200) {
    return true;
  }
  if (msgFlag && response.msg) ElMessage.error(response.msg);
  return false;
};
